﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Panda.DynamicWebApi;
using Panda.DynamicWebApi.Attributes;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WareHouse.Domain.Procurements;
using WareHouse.Repositories;
//using Microsoft.EntityFrameworkCore.Infrastructure;
using WareHouse.Domain.ModelClass;
using WareHose.Application.Procurements.Dto;
using WareHose.Application.Warehouse.Dto;
using System.Security.Cryptography;
using WareHouse.Domain.SupplierManagement;
using WareHouse.Domain.Warehouses;

namespace WareHose.Application.Procurements
{
    /// <summary>
    /// 采购管理
    /// </summary>
    [DynamicWebApi]
    [ApiExplorerSettings(GroupName = "v2")]
    public class ProcurementServices : IDynamicWebApi
    {
        private readonly IBaseRepository<Procurement> _procurement;
        private readonly IBaseRepository<ProcurementReturn> _procurementReturn;
        private readonly IBaseRepository<Shopping> _shopping;
        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="procurement"></param>
        /// <param name="procurementReturn"></param>
        /// <param name="shopping"></param>
        /// <param name="mapper"></param>
        /// <param name="db"></param>
        public ProcurementServices(IBaseRepository<Procurement> procurement, IBaseRepository<ProcurementReturn> procurementReturn, IBaseRepository<Shopping> shopping, IMapper mapper, ISqlSugarClient db)
        {
            _procurement = procurement;
            _procurementReturn = procurementReturn;
            _shopping = shopping;
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 分页显示采购
        /// </summary>
        /// <param name="procurementCode"></param>
        /// <param name="productId"></param>
        /// <param name="productName"></param>
        /// <param name="procurementStatus"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultDto<PagingDto<ProcurementDto>>> ShowProcurement(string procurementCode,string productId,string productName, ProcurementStatus procurementStatus, int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var list = await db.Queryable<Procurement, Shopping, ProductInfo, Supplier>((a, b, c, d) => new JoinQueryInfos(
                    JoinType.Left, b.ProcurementCode == a.ProcurementCode,
                    JoinType.Left, b.ProductId == c.ProductId,
                    JoinType.Left, a.SupplierId == d.Id
                    ))
                    .Where(a=>a.IsDel==false)
                    .Select((a, b, c,d) => new ProcurementDto
                    {
                        ProcurementId = a.ProcurementId.ToString(),
                        ProcurementCode = a.ProcurementCode,
                        ProductName = c.ProductName,
                        ProductId = c.ProductId.ToString(),
                        Specification = c.Specification,
                        Unit = c.Unit,
                        Price = c.Price,
                        BuyNumber = b.BuyNumber,
                        SumPrice = b.SumPrice,
                        ProcurementStatus=a.ProcurementStatus
                    })
                     .WhereIF(!string.IsNullOrEmpty(procurementCode), a => a.ProcurementCode.Contains(procurementCode))
                    .WhereIF(!string.IsNullOrEmpty(productId),c=>c.ProductId.Contains(productId))
                    .WhereIF(!string.IsNullOrEmpty(productName), c => c.ProductName.Contains(productName))
                    .WhereIF(procurementStatus != 0, a => a.ProcurementStatus== procurementStatus)
                    .ToPageListAsync(pageIndex,pageSize);
                return new ResultDto<PagingDto<ProcurementDto>>
                {
                    Code = Status.Success,
                    Data = new PagingDto<ProcurementDto>
                    {
                        TotalRows = list.Count,
                        Rows = list
                    }
                };
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 添加采购单
        /// </summary>
        /// <param name="procurementInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultDto> AddProcurement(AddOrUpdProcurementDto procurementInfo)
        {
            //开启事务
            db.Ado.BeginTran();
            try
            {
                
                var entity = mapper.Map<AddOrUpdProcurementDto, Procurement>(procurementInfo);
                await _procurement.InsertAsync(entity);
                foreach (var item in procurementInfo.ProcurementProductDto)
                {
                    Shopping shopping = new Shopping();
                    shopping.ProductId = item.ProductId.ToString();
                    shopping.ProcurementCode = procurementInfo.ProcurementCode;
                    shopping.BuyNumber = item.BuyNumber;
                    shopping.SumPrice = item.BuyNumber * item.Price;
                    await _shopping.InsertAsync(shopping);
                }
                //提交事务
                db.Ado.CommitTran();
                return new ResultDto
                {
                    Code = Status.Success,
                    Message = "添加成功"
                };
            }
            catch (Exception)
            {
                //回滚事务
                db.Ado.RollbackTran();
                throw;
            }
        }


        /// <summary>
        /// 枚举转下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ResultDto<object> ShowProcurementState()
        {
            List<object> list = new List<object>();
            foreach (var item in Enum.GetValues<ProcurementStatus>())
            {
                list.Add(new
                {
                    value = item,
                    label = item.ToString()
                });
            }
            return new ResultDto<object> { Code = Status.Success, Data = list };
        }

        /// <summary>
        /// 逻辑删除产品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ResultDto> DelProcurement(long id)
        {
            try
            {
                var entity = await _procurement.FistAsync(x => x.ProcurementId == id);
                if (entity != null)
                {
                    await _procurement.Delete(id);
                    return new ResultDto
                    {
                        Code = Status.Success,
                        Message = "删除成功"
                    };
                }
                else
                {
                    return new ResultDto
                    {
                        Code = Status.Failed,
                        Message = "删除失败"
                    };
                }
            }
            catch (Exception)
            {

                throw;
            }


            ////开启事务
            //db.Ado.BeginTran();
            //try
            //{
            //    var list = await _shopping.FistAsync(x => x.ShoppingId == id);
            //    await _shopping.Delete(id);
            //    var list1 = await _shopping.QueryAsync(x => x.ProcurementCode == list.ProcurementCode);
            //    if (list1.Count == 0)
            //    {
            //        var list2 = await _procurement.FistAsync(x => x.ProcurementCode == list.ProcurementCode);
            //        await _procurement.Delete(list2.ProcurementId);
            //    }
            //    //提交事务
            //    db.Ado.CommitTran();
            //    return new ResultDto
            //    {
            //        Code = Status.Success,
            //        Message = "删除成功"
            //    };
            //}
            //catch (Exception)
            //{
            //    //回滚事务
            //    db.Ado.RollbackTran();
            //    throw;
            //}
        }

        /// <summary>
        /// 反填采购信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultDto<ProcurementDto>> BackFillProcurement(string id)
        {
            try
            {
                var info = await _procurement.FistAsync(x => x.ProcurementId.ToString() == id);
                var procurementDto = mapper.Map<ProcurementDto>(info);
                return new ResultDto<ProcurementDto>
                {
                    Code = Status.Success,
                    Data = procurementDto
                };
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 反填采购商品信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultDto<List<ProcurementProductDto>>> BackFillShopping(string code)
        {
            try
            {
                //var info = await db.Queryable<Shopping>().Where(x=>x.ProcurementCode == code).ToListAsync();
                //var list = mapper.Map<List< ProcurementProductDto>>(info);
                var list = await db.Queryable<Shopping, ProductInfo>((a, b) => new
                    JoinQueryInfos(
                        JoinType.Left, a.ProductId == b.ProductId
                    ))
                    .Where((a,b)=>a.ProcurementCode==code)
                    .Select((a,b)=>new ProcurementProductDto
                    {
                        ShoppingId=a.ShoppingId.ToString(),
                        ProductId=a.ProductId.ToString(),
                        ProcurementCode=a.ProcurementCode,
                        Price=b.Price,
                        BuyNumber=a.BuyNumber,
                        SumPrice=a.SumPrice,
                    })
                    .ToListAsync();
                return new ResultDto<List<ProcurementProductDto>>
                {
                    Code = Status.Success,
                    Data = list
                };
            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 修改采购单
        /// </summary>
        /// <param name="procurementInfo"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ResultDto> UpdProcurement(AddOrUpdProcurementDto procurementInfo)
        {
            //开启事务
            db.Ado.BeginTran();
            try
            {

                var entity = mapper.Map<AddOrUpdProcurementDto, Procurement>(procurementInfo);
                await _procurement.UpdateAsync(entity);
                foreach (var item in procurementInfo.ProcurementProductDto)
                {
                    Shopping shopping = new Shopping();
                    shopping.ProductId = item.ProductId.ToString();
                    shopping.ProcurementCode = procurementInfo.ProcurementCode;
                    shopping.BuyNumber = item.BuyNumber;
                    shopping.SumPrice = item.BuyNumber * item.Price;
                    await _shopping.UpdateAsync(shopping);
                }
                //提交事务
                db.Ado.CommitTran();
                return new ResultDto
                {
                    Code = Status.Success,
                    Message = "修改成功"
                };
            }
            catch (Exception)
            {
                //回滚事务
                db.Ado.RollbackTran();
                throw;
            }
        }
    }
}
